import axios from 'axios'
import buildURL from 'axios/lib/helpers/buildURL'
import { merge, isPlainObject } from 'axios/lib/utils'
import { Toast } from 'antd-mobile'


let acitveAxios = 0
let loadingFlag
let timer

const setLoading = loadingText => {
  if (!loadingFlag && acitveAxios > 0) {
    loadingFlag = true
    Toast.loading(loadingText || '加载中...', 0)

    // 优化loading的显示，保证用250ms的时间显示loading
    // 避免请求响应在400-600ms之间时，loading闪现问题（loading还未来得及显示就关闭了）
    if (acitveAxios === 1) {
      acitveAxios++
      setTimeout(closeLoading, 350)
    }
  }
}

const showLoading = loading => {
  if (loading !== undefined && !loading) {
    return
  }
  acitveAxios++
  timer = timer && clearTimeout(timer)
  if (loading) {
    setLoading(loading)
  } else {
    // 400ms内请求还有没有响应则显示loading
    timer = setTimeout(setLoading, 400)
  }
}

const closeLoading = () => {
  acitveAxios--
  if (acitveAxios <= 0) {
    timer = timer && clearTimeout(timer)
    loadingFlag = false    
    Toast.hide()
  }
}

// 请求拦截
const requestInterceptors = [
  cfg => {
    showLoading(cfg.loading)

    /* if (store.state.token) {
      cfg.headers.Authorization = 'Bearer ' + store.state.token
    } */

    // 表单提交
    if (cfg.emulateJSON && isPlainObject(cfg.data)) {
      cfg.data = buildURL('', cfg.data).substr(1)
    }
    // console.log(cfg)
    return cfg
  }
]

// 响应拦截
const responseInterceptors = [
  res => {
    closeLoading()

    const { config: cfg, data } = res
    res.ok = true
    if (typeof cfg.errMsg === 'undefined') {
      cfg.errMsg = '系统繁忙！'
    }

    if (!cfg.disableInterceptor) {      
      const { code, message } = data
      if (code === 0) {
        return data
      } else {
        // 其他请求错误
        cfg.errMsg && Toast.fail(message || cfg.errMsg, 3)
        return Promise.reject(data)
      }
    }
    return data
  },
  err => {
    closeLoading()
    const { request: req } = err
    err.ok = false
    const msg = statusText[req.status] || `请求异常，请联系技术支持（${req.statusText || err.message}）`
    Toast.fail(msg, 3)
    return Promise.reject(err)
  }
]

const statusText = {
  0: '网络错误，请稍后再试',
  400: '请求参数异常',
  10: '数据错误',
  404: '请求不存在',
  // '401': '没有访问权限！',
  403: '密码错误或账号不存在！'
}

const defaults = {
  baseURL: '/api'
  // disableInterceptor: true
  // timeout: 15000, // 默认请求超时/ms
  // emulateJSON: true, // 是否默认表单提交
}

// 取消请求
const CancelToken = axios.CancelToken
const cancelSource = CancelToken.source()

export const serviceCreate = config => {
  const service = axios.create(merge(defaults, config))
  service.interceptors.request.use(...requestInterceptors)
  service.interceptors.response.use(...responseInterceptors)
  return service
}

export { merge, cancelSource }
export const service = serviceCreate()
